/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package nl.rainbowsheep.reisorg.cust.site.authentication;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import nl.rainbowsheep.reisorg.cust.site.model.BurritoRole;
import nl.rainbowsheep.reisorg.cust.site.model.BurritoUser;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.web.client.RestTemplate;

/**
 *
 * @author ieme
 */
public class UserDetailsServiceImpl implements UserDetailsService {

    @Value("${api.url}") 
    String url;
    
    @Override
    public UserDetails loadUserByUsername(final String username)
            throws UsernameNotFoundException {

        final RestTemplate template = new RestTemplate();
        final List<ClientHttpRequestInterceptor> interceptors = new ArrayList<ClientHttpRequestInterceptor>();
        interceptors.add(new BasicAuthInterceptor());
        template.setInterceptors(interceptors);
        BurritoUser g = template.getForObject(url + "user/getUserByName?name=" + username, BurritoUser.class);
        List<GrantedAuthority> authorities = buildUserAuthority(g.getBurritoUserRoles());
        return (UserDetails) buildUserForAuthentication(g, authorities);
    }

    private User buildUserForAuthentication(nl.rainbowsheep.reisorg.cust.site.model.BurritoUser user,
            List<GrantedAuthority> authorities) {
        return new User(user.getUsername(),
                user.getPassword(), user.isEnabled(),
                true, true, true, authorities);
    }

    private List<GrantedAuthority> buildUserAuthority(Set<BurritoRole> userRoles) {

        Set<GrantedAuthority> setAuths = new HashSet<GrantedAuthority>();

        // Build user's authorities
        for (BurritoRole userRole : userRoles) {
            setAuths.add(new SimpleGrantedAuthority(userRole.getBurritoRole()));
        }

        List<GrantedAuthority> Result = new ArrayList<GrantedAuthority>(setAuths);

        return Result;
    }

}
